<template>
  <div>
    <common-layout>
      <div id="startsAimate" v-show="startsAimate">
        <img alt="logo" class="logo1 animate__animated animate__rotateOut" src="@/assets/img/logo.png" />
        <div class="title animate__animated animate__fadeOut">指南针</div>
      </div>
      <div v-show="!startsAimate">
        <a-row class="login" type="flex" justify="center">
          <div class="left animate__animated animate__fadeInLeft">
            <img alt="logo" class="logo animate__animated animate__rotateIn animate__delay-1s" src="@/assets/img/logo.png" />
            <img alt="指南针" class="text animate__animated animate__fadeInUp animate__delay-1s" src="@/assets/img/text.png" />
            <!-- <div class="talent">
            我们一起寻找新大陆
          </div>
          <div class="kh">
            以推动天下蓝领快乐工作、幸福生活为己任<br />
            成为全球蓝领首选的终身服务平台
          </div> -->
          </div>
          <div class="right animate__animated animate__fadeInRight">
            <div class="tips">钉钉扫码后点击“确认授权”，即可完成账号绑定及登录。<br />支持APP扫码登录</div>
            <div id="login_container"></div>
            <div class="help">扫码无法登录？<br />请联系上级主管或HR确认钉钉是否已加入企业。</div>
          </div>
        </a-row>
        <div class="animate__animated animate__fadeInUp animate__delay-2s">
          <div class="copyright ">
            指南针 · 我们一起寻找新大陆
          </div>
        </div>
      </div>
    </common-layout>
    <canvas id="canvas"></canvas>
  </div>
</template>

<script>
import CommonLayout from '@/layouts/CommonLayout'
import { tkLogin, getMenu } from '@/services/user'
import { setAuthorization } from '@/utils/request'
import { loadRoutes } from '@/utils/routerUtil'
import { mapMutations } from 'vuex'
import { start } from '@/utils/start'


export default {
  name: 'Login',
  components: { CommonLayout },
  data () {
    return {
      startsAimate: true,
      code: "",
      logging: false,
      error: '',
      form: this.$form.createForm(this)
    }
  },
  computed: {
    systemName () {
      return this.$store.state.setting.systemName
    }
  },
  mounted () {
    let token = this.$Storage.get('token')
    console.log('token', token)
    // 群星宇宙
    start()
    // 动画
    this.animateInit()
    // 如果存在token自动跳转工作台
    if (token) {
      this.$router.push('/workplace')
    } else {
      localStorage.clear()
      // code是登录所需最终参数
      const { code } = this.$route.query
      this.$Storage.set('url', window.location.href)
      console.log('code', code)
      if (code) { // 登录接口
        this.goWorkPlace(code)
      } else { // 钉钉二维码
        this.ddLoginInit()
      }
    }
  },
  methods: {
    ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles']),
    // 动画初始化
    animateInit () {
      let that = this
      const element = document.querySelector('#startsAimate');
      element.classList.add('animate__animated', 'animate__fadeOut', 'animate__slower');
      element.addEventListener('animationend', () => {
        that.startsAimate = false
      });
    },
    ddLoginInit () {
      // 根据环境变量配置钉钉环境回调
      let config = {
        development: {
          url: 'http://localhost:8080/#/login',
          appid: 'dingoa9pyb9i6fljfan9v8'
        },
        test: {
          url: 'http://test-cp.tking.com/#/login',
          appid: 'dingoakln867f37kuvrott'
        },
        production: {
          url: 'http://cp.tking.com/#/login',
          appid: 'dingoapz7tqginauluqukg'
        },
      }
      let { url, appid } = config[process.env.NODE_ENV]

      console.log('config', process.env.NODE_ENV, url, appid)
      // 钉钉扫码流程：扫码成功登录后会自动跳到这个url页面，url路径会携带code，你拿到这个code，调用登录接口成功就跳转。
      // 你的项目页面
      url = encodeURIComponent(url);
      // 钉钉自己的url 修改上面俩，不需要动这个
      let u = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`
      let goto = encodeURIComponent(u)
      let obj = window.DDLogin({
        id: "login_container", // 这里需要你在自己的页面定义一个HTML标签并设置id，例如<div id="login_container"></div>或<span id="login_container"></span>
        goto: goto, // 请参考注释里的方式
        style: "border:none;background-color:#FFFFFF;",
        width: "100%", // 官方参数 365
        height: "300" // 官方参数 400
      });
      console.log(obj)
      let handleMessage = (event) => {
        let origin = event.origin;
        if (origin == "https://login.dingtalk.com") { // 判断是否来自ddLogin扫码事件。
          let loginTmpCode = event.data;
          // 获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
          console.log("loginTmpCode", loginTmpCode);
          this.$Storage.set('loginTmpCode', loginTmpCode)
          // 此步拿到临时loginTmpCode换取正式code
          // window.location.href = `${u}&loginTmpCode=${loginTmpCode}`;
          window.location.replace(`${u}&loginTmpCode=${loginTmpCode}`);
        }
      };
      if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false);
      } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage);
      }
    },
    goWorkPlace (code) {
      // 获取token
      let prams = {
        channelType: 'CATFISH_PC',
        loginType: 'DING',
        ddScanCode: code
      }
      tkLogin(prams).then(this.afterLogin)
    },
    afterLogin (res) {
      this.logging = true
      const loginRes = res.data
      if (loginRes.code == 200) {
        const { user, token, authorityList } = loginRes.data
        // console.log('login', loginRes)
        this.setUser(user)
        // this.setPermissions(permissions)
        // this.setRoles(userRoleList)
        setAuthorization({ token })
        this.$Storage.set('token', token)
        // 获取路由配置 loginRes.data.authorityList
        getMenu().then(result => {
          let { code } = result.data
          // console.log('222', code, data)
          this.$Storage.set('menu', authorityList)
          if (code == 200) {
            this.logging = false
            this.$message.success('欢迎回来', 3)
            loadRoutes(this.searchCode(authorityList))
            // this.$router.replace('/workplace')
            this.$router.push('/workplace')
          }
        })
      } else {
        this.$router.replace('/login')
        this.$message.error(loginRes.msg, 6)
      }
    },
    searchCode (list) {
      let arr = []
      list.forEach((item) => {
        let items = {}
        if (item?.children.length > 0) {
          items.router = item.router
          items.children = item.children.map(item => item.router)
          this.searchCode(item.children)
        } else {
          items.router = item.router
        }
        arr.push(items)
      });
      return [
        {
          "router": "root",
          "children": arr
        }
      ]
    }
  }
}
</script>

<style lang="less" scoped>
body {
  margin: 0 auto;
  overflow: hidden;
}
canvas {
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
}
#startsAimate {
  text-align: center;
  .logo1 {
    height: 15vh;
  }
  .title {
    font-size: 30px;
    color: #fff;
    margin: 30px;
  }
}
.common-layout {
  display: grid;
  place-items: center;
  .login {
    width: 1000px;
    min-height: 560px;
    box-shadow: 0px 6px 20px 0px rgba(59, 115, 248, 0.1);
    border-radius: 16px;
    overflow: hidden;
    margin: 0 auto;
    box-sizing: border-box;
  }
  .left {
    width: 428px;
    padding: 3.6% 0 3.6% 3.6%;
    background-color: #3370ff;
    color: #ffffff;
    background-image: url(../../assets/img/left.jpg);
    background-size: cover;
    .logo {
      height: 5.7vh;
    }
    .text {
      height: 4.8vh;
      margin-left: 10px;
    }
    .talent {
      font-size: 40px;
      padding: 26% 0 36% 0;
    }
    .kh {
      font-size: 16px;
      font-family: Helvetica;
    }
  }
  .right {
    width: 572px;
    padding: 8% 0;
    background-color: #fff;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    .tips,
    .help {
      padding: 0 5%;
      text-align: center;
    }
    .tips {
      color: #222222;
      font-weight: bold;
    }
    .help {
      color: #888888;
    }
  }
}
.copyright {
  text-align: center;
  margin: 30px auto;
  width: 40%;
  color: #fff;
  position: relative;
  .lineCom(@direction) {
    position: absolute;
    content: "";
    top: 50%;
    width: 20%;
    height: 1px;
    @{direction}: 0;
    background-image: linear-gradient(to @direction, #fff, transparent);
  }
  &:before {
    .lineCom(left);
  }
  &:after {
    .lineCom(right);
  }
}
</style>
